#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define N_WRITER 3		//写者数目
#define N_READER 5		//读者数目
#define W_SLEEP  1		//控制写频率
#define R_SLEEP  1		//控制读频率

pthread_t wid[N_WRITER], rid[N_READER];  //声明线程ID
pthread_mutex_t writeLock = PTHREAD_MUTEX_INITIALIZER;
   //定义互斥锁并初始化 
pthread_mutex_t accessReaderCnt = PTHREAD_MUTEX_INITIALIZER;

int data = 0;    //读写的是数据
int readerCnt = 0;


void my_write()
{
	int rd = rand();  //得到随机数
	data = rd;
 //写了一个随机数
	printf("write: %d \n",rd);
}
void my_read()
{
	printf("read %d\n", data);
}   //输出读到的数

void * my_reader(void *in)
{
	while (1) {
		pthread_mutex_lock(&accessReaderCnt);
		readerCnt++;
		if (readerCnt == 1) {
			pthread_mutex_lock(&writeLock);
		}
		pthread_mutex_unlock(&accessReaderCnt);
		my_read();
		pthread_mutex_lock(&accessReaderCnt);
		readerCnt--;
		if (readerCnt == 0) {
			pthread_mutex_unlock(&writeLock);
		}
		pthread_mutex_unlock(&accessReaderCnt);
		sleep(R_SLEEP);
	}
	pthread_exit((void *)0);
}





void *my_writer(void *in)
{
	while (1) {
		pthread_mutex_lock(&writeLock);
		my_write();
		pthread_mutex_unlock(&writeLock);
		sleep(W_SLEEP);
	}
	pthread_exit((void *)0);
}

int main()
{
	int i = 0;
	for (i = 0; i < N_READER; i++) {
		pthread_create(&wid[i], NULL, my_reader, NULL);
	}
	for (i = 0; i < N_WRITER; i++) {
		pthread_create(&rid[i], NULL, my_writer, NULL);
	}
	while (1) {
		sleep(10);
	}
	return 0;
}

